//
//  ImageViewController.swift
//  SwiftCode
//
//  Created by 于虎拴 on 2023/2/20.
//

import Foundation
import UIKit
import SnapKit
import RxSwift

class ImageViewController: UIViewController {
  private let bag = DisposeBag()
  
  public init(url: URL) {
    super.init(nibName: nil, bundle: nil)
    
    DispatchQueue.global(qos: .utility).async { [weak self] in
      // 这里如果是 Strong self 其实也是不会造成引用循环的。因为这个任务执行的 closure 一执行完毕就会销毁掉的。
      guard let self, let data = try? Data(contentsOf: url),
            let image = UIImage(data: data) else { return }
      // 切换到主线程刷新任务
      
      DispatchQueue.main.async {
        self.imageView.image = image
      }
    }
  }
  
  public init() {
    super.init(nibName: nil, bundle: nil)
  }
  
  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.backgroundColor = .black
    
    view.addSubview(imageView)
    imageView.snp.makeConstraints { make in
      make.edges.equalToSuperview()
    }
    
    initData()
  }
  
  private func initData() {
    imageView.rx.tapGesture()
      .when(.recognized)
      .subscribe(onNext: { [weak self] _ in
        self?.dismiss(animated: true)
      })
      .disposed(by: bag)
  }
  
  private(set) lazy var imageView: UIImageView = {
    let imageView = UIImageView()
    imageView.contentMode = .center
    return imageView
  }()
}
